﻿using EP.Base.BaseService.Manager.Business.QzJob;
using EP.Base.BaseService.Manager.Config;
using EP.Base.BaseService.Manager.Interface.Business;
using EP.Base.BaseService.Manager.Interface.Common;
using Quartz;
using Quartz.Impl;

namespace EP.Base.BaseService.Manager.Business.Scheduler
{
    /// <summary>
    /// 所有任务公用一个job，每次job执行时遍历执行所有任务
    /// </summary>
    public class EsServiceSchedulerAutoMonitor:IAutoMonitorService
    {
        private readonly ILog _log;
        private readonly IEsMaintainTask _esMaintainTask;
        private readonly IServiceSimplifyLog _serviceSimplifyLog;
        //从工厂中获取一个调度器实例化
        IScheduler _scheduler;
        private readonly string _cron = EsMaintainTaskConfig.TaskSchedule;
        public EsServiceSchedulerAutoMonitor(ILog log, IEsMaintainTask esMaintainTask, IServiceSimplifyLog serviceSimplifyLog)
        {
            _log = log;
            _esMaintainTask = esMaintainTask;
            _serviceSimplifyLog = serviceSimplifyLog;
        }

        public void Start()
        {
            _serviceSimplifyLog.ExecSl("创建定时任务,计划="+_cron,()=>
            {
                _scheduler = StdSchedulerFactory.GetDefaultScheduler();
                //开启调度器
                _scheduler.Start();
                //创建一个作业
                IJobDetail srcInitJob = JobBuilder.Create<EsMaintainTaskQzJob>()
                    .WithIdentity("任务", "定时任务")
                    .Build();
                srcInitJob.JobDataMap.Add("IEsMaintainTask", _esMaintainTask);
                srcInitJob.JobDataMap.Add("IServiceSimplifyLog", _serviceSimplifyLog);
                srcInitJob.JobDataMap.Add("ILog", _log);
                //定义触发器
                ITrigger trigger = TriggerBuilder.Create()
                                    .WithIdentity("任务触发器", "定时任务触发器")
                                    .StartNow()                        //现在开始
                                    .WithCronSchedule(_cron)             //cron表达式
                                    .Build();

                //把作业，触发器加入调度器。
                _scheduler.ScheduleJob(srcInitJob, trigger);

            });
           
        }

        public void WriteDebugMsg(string msg)
        {
            _log.Debug(msg);
        }

        public void WriteErrorMsg(string msg)
        {
            _log.Error(msg);
        }

        public void Stop()
        {
            _serviceSimplifyLog.ExecSl("停止定时任务", () =>
            {
                if (_scheduler != null)
                    _scheduler.Shutdown();
            });
        }

        public void Dispose()
        {
           //
        }
    }
}
